<template>
	<view class="app register">
		<!-- 页面内容开始 -->
		<view class="content">
			<!-- 头部logo -->
			<view class="header">
				<!-- <u-image class="logo" :src="form1.avatar"></u-image> -->
				<button class="avatar" plain open-type="chooseAvatar" @chooseavatar="onChooseAvatar" @click="chooseAvatar">
					<image v-if="form1.avatar" style="width: 100%; height: 100%" :src="form1.avatar" mode="aspectFill" :fade="false"></image>
					<text v-else>头像</text>
				</button>
			</view>
			<!-- 主体 -->
			<view class="form-view">
				<view class="form-item form-border">
					<!-- 文本框 -->
					<input class="form-input" v-model="form1.mobile" type="text" :maxlength="11" placeholder="手机号" placeholder-style="'color':'#8e8e8e'" />
				</view>

				<view class="form-item form-border">
					<!-- 文本框 -->
					<!-- #ifdef MP-WEIXIN -->
					<input class="form-input" v-model="form1.nickname" type="nickname" :maxlength="20" placeholder="请输入昵称" placeholder-style="'color':'#8e8e8e'" />
					<!-- #endif -->
					<!-- #ifndef MP-WEIXIN -->
					<input class="form-input" v-model="form1.nickname" type="text" :maxlength="20" placeholder="请输入昵称" placeholder-style="'color':'#8e8e8e'" />
					<!-- #endif -->
				</view>

				<view class="form-item form-border">
					<!-- 文本框 -->
					<input class="form-input" v-model="form1.password" type="password" placeholder="请输入新密码" placeholder-style="'color':'#8e8e8e'" />
				</view>
				<view class="form-item form-border">
					<!-- 文本框 -->
					<input class="form-input" v-model="form1.password2" type="password" placeholder="请再次输入新密码" placeholder-style="'color':'#8e8e8e'" />
				</view>

				<view class="form-item form-border">
					<!-- 文本框 -->
					<input class="form-input" v-model="form1.code" type="number" :maxlength="6" placeholder="请输入短信验证码" placeholder-style="'color':'#8e8e8e'" />
					<!-- 验证码倒计时开始 -->
					<vk-data-verification-code seconds="60" :mobile="form1.mobile" type="register" custom-style="font-size: 28rpx;"></vk-data-verification-code>
					<!-- 验证码倒计时结束 -->
				</view>

				<view class="form-item form-border">
					<!-- 文本框 -->
					<input class="form-input" v-model="form1.inviteCode" type="text" :maxlength="11" placeholder="邀请码" placeholder-style="'color':'#8e8e8e'" />
				</view>
			</view>
			<view class="submit-btn">
				<button class="btn success circle" hover-class="hover" shape="circle" @click="loginBySms" :plain="false" :hair-line="false" type="success">注 册</button>
			</view>
			<!-- 底部信息 -->
			<view class="footer" style="margin-bottom: 100rpx">
				<label>
					<checkbox-group @change="checkboxChange">
						<checkbox class="footer-checkbox" value="true" :checked="form1.agreement" active-color="#737373" shape="circle"></checkbox>
						<text>同意</text>
					</checkbox-group>
				</label>

				<!-- 协议地址 -->
				<navigator url="./agreement" open-type="navigate" class="link">《用户协议》</navigator>
				<!-- #ifdef MP-WEIXIN -->
				<text>和</text>
				<text class="link" @click="openPrivacyContract">《隐私协议》</text>
				<!-- #endif -->
			</view>
		</view>

		<!-- #ifdef MP-WEIXIN -->
		<!-- 微信小程序专用隐私授权弹窗组件 -->
		<vk-mall-privacy-popup position="bottom" @agree="userAgreement"></vk-mall-privacy-popup>
		<!-- #endif -->

		<!-- 页面内容结束 -->
	</view>
</template>

<script>
var vk = uni.vk; // vk依赖
export default {
	data() {
		// 页面数据变量
		return {
			// init请求返回的数据
			data: {},
			// 表单请求数据
			form1: {
				agreement: true,
				nickname: "",
				mobile: "",
				password: "",
				password2: "",
				code: "",
				type: "register",
				inviteCode: "",
				avatar: ""
			},
			scrollTop: 0,
			isRotate: false,
			logoImage: "/static/logo.png",
			uploadList: []
		};
	},
	onPageScroll(e) {
		this.scrollTop = e.scrollTop;
	},
	// 监听 - 页面每次【加载时】执行(如：前进)
	onLoad(options) {
		vk = uni.vk;
		this.init(options);
		uni.$on("uAvatarCropper", this.updateAvatar);
	},
	// 监听 - 页面【首次渲染完成时】执行。注意如果渲染速度快，会在页面进入动画完成前触发
	onReady() {},
	// 监听 - 页面每次【显示时】执行(如：前进和返回) (页面每次出现在屏幕上都触发，包括从下级页面点返回露出当前页面)
	onShow() {},
	// 监听 - 页面每次【隐藏时】执行(如：返回)
	onHide() {},
	// 监听 - 页面每次【卸载时】（一般用于取消页面上的监听器）
	onUnload() {
		uni.$off("uAvatarCropper", this.updateAvatar);
	},
	// 监听 - 点击右上角转发时
	onShareAppMessage(options) {},
	// 函数
	methods: {
		// 页面数据初始化函数
		init(options = {}) {
			let that = this;
			console.log("init: ", options);
			let logo = vk.getVuex("$user.mchInfo.logo");
			if (logo) that.logoImage = logo;
			if (options.mobile) that.form1.mobile = options.mobile;
			if (!that.form1.inviteCode) {
				that.form1.inviteCode = vk.getVuex("$user.inviteCode");
			}
		},
		pageTo(path) {
			vk.navigateTo(path);
		},
		checkboxChange(e) {
			let that = this;
			let value = e.detail.value || [];
			if (value.length > 0 && value[0]) {
				that.form1.agreement = true;
			} else {
				that.form1.agreement = false;
			}
		},
		// 登录(手机号+验证码) 不存在会自动注册
		async loginBySms() {
			let that = this;
			if (that.isRotate) {
				//判断是否加载中，避免重复点击请求
				return false;
			}
			const { avatar, agreement, nickname, mobile, code, password, password2 } = that.form1;
			if (!agreement) {
				vk.toast("请阅读并同意用户服务及隐私协议");
				return;
			}
			if (!avatar) {
				vk.toast("头像不能为空");
				return;
			}
			if (!nickname) {
				vk.toast("昵称不能为空");
				return;
			}
			if (!vk.pubfn.checkStr(mobile, "mobile")) {
				vk.toast("请输入正确的手机号码");
				return;
			}
			if (!vk.pubfn.checkStr(password, "pwd")) {
				vk.toast("密码以字母开头，长度在6~18之间，只能包含字母、数字和下划线");
				return;
			}
			if (!vk.pubfn.checkStr(password2, "pwd")) {
				vk.toast("密码以字母开头，长度在6~18之间，只能包含字母、数字和下划线");
				return;
			}
			if (password != password2) {
				vk.toast("两次密码必须相同!");
				return;
			}
			if (!vk.pubfn.checkStr(code, "mobileCode")) {
				vk.toast("验证码格式为6位数字");
				return;
			}
			if (that.uploadList.indexOf(avatar) == -1) {
				// 如果此头像没有上传过，则先上传
				await vk.uploadFile({
					title: "上传中...",
					filePath: avatar,
					suffix: "png", // 不传suffix会自动获取，但H5环境下获取不到后缀，但可以通过file.name 获取
					success: res => {
						// 上传成功
						that.uploadList.push(res.url);
						that.form1.avatar = res.url;
					}
				});
			}
			that.isRotate = true;
			vk.userCenter.loginBySms({
				data: that.form1,
				success: data => {
					that.isRotate = false;
					if (data.type == "login") {
						vk.toast("登录成功!");
					} else {
						vk.toast("注册成功!");
					}
					setTimeout(() => {
						vk.setVuex("$user.login.username", mobile);
						vk.setVuex("$user.login.password", password);
						vk.setVuex("$user.login.savePwd", true);
						// 跳转到首页,或页面返回
						let pages = getCurrentPages();
						if (pages.length >= 2 && pages[pages.length - 2].route && pages[pages.length - 2].route.indexOf("login") == -1) {
							vk.navigateBack();
						} else {
							// 进入首页
							vk.navigateToHome();
						}
					}, 1000);
				},
				complete: () => {
					that.isRotate = false;
				}
			});
		},
		// 监听 - 微信头像选择器
		onChooseAvatar(e) {
			const { avatarUrl } = e.detail;
			if (avatarUrl) {
				this.form1.avatar = avatarUrl;
			}
		},
		chooseAvatar() {
			// #ifndef MP-WEIXIN
			this.$u.route({
				url: "/uni_modules/vk-uview-ui/components/u-avatar-cropper/u-avatar-cropper",
				params: {
					// 输出图片宽度，高等于宽，单位px
					destWidth: 300,
					// 裁剪框宽度，高等于宽，单位px
					rectWidth: 200,
					// 输出的图片类型，如果'png'类型发现裁剪的图片太大，改成"jpg"即可
					fileType: "jpg"
				}
			});
			// #endif
		},
		// 修改头像
		updateAvatar(avatar) {
			let that = this;
			if (avatar.indexOf(";base64,") > -1) {
				// 上传到云存储
				vk.pubfn.base64ToFile({
					base64: avatar,
					success: file => {
						this.form1.avatar = file.path;
					}
				});
			} else {
				this.form1.avatar = avatar;
			}
		},
		userAgreement(){
			this.form1.agreement = true;
		},
		// 打开隐私协议页面
		openPrivacyContract() {
			uni.openPrivacyContract({
				success: () => {
					this.isRead = true;
				},
				fail: (err) => {
					console.error('err: ', err)
					uni.showToast({
						title: '网络错误',
						icon: 'error'
					});
				}
			});
		},
	},
	// 计算属性
	computed: {}
};
</script>
<style lang="scss" scoped>
@import url("./css/main.css");
.avatar {
	width: 160rpx;
	height: 160rpx;
	border-radius: 50%;
	margin: 0;
	padding: 0;
	border: 1px solid #f8f8f8;
	display: flex;
	justify-content: center;
	align-items: center;
}
</style>
